package com.ruoyi.translate.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.translate.domain.HtImport;
import com.ruoyi.translate.domain.Identify;
import com.ruoyi.translate.domain.ShiBieVo;
import com.ruoyi.translate.domain.Words;
import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @ClassName: TranslateUtil
 * @Author: chenJie
 * @Description:
 */
public class TranslateUtil {

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    private static final String API_KEY = "RhXVFCSHm3S5fsNXIUEYrXjK";
    private static final String CLIENT_SECRET = "2BxSAmbe9KkQ0f5Xq893GKvdujnGsHos";
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static List<Words> shiBie(String url) {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        try {
            String encodedUrl = URLEncoder.encode(url, StandardCharsets.UTF_8.toString());
            RequestBody body = RequestBody.create(mediaType, "url=" + encodedUrl + "&detect_direction=false&probability=false&detect_alteration=false");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            String string = response.body().string();
            Identify identify = objectMapper.readValue(string, Identify.class);
            return identify.getWords_result();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + CLIENT_SECRET);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }
}
